package com.itheima.health.security;

import com.itheima.health.entity.UserConstant;
import com.itheima.health.utils.jwt.UserInfo;
import com.itheima.health.utils.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

//    @Reference
//    private UserService userService;   调用远程 服务 获取用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //  根据 账号  查询数据库   账号  密码  权限信息  封装  UserDetails
        //   redis   key    username   密码   权限信息 。。。
//        JSONObject o = (JSONObject) RedisUtil.get(UserConstant.SYSUSERINFO + username);
//        UserInfo userInfo = o.toJavaObject(UserInfo.class);
        UserInfo userInfo = (UserInfo) RedisUtil.get(UserConstant.SYSUSERINFO + username);
        String password = passwordEncoder.encode(userInfo.getPassword());
        System.out.println("==="+password);
        String roles = userInfo.getRoles();  //  xx,xx,xx,xx
        List<GrantedAuthority> authorities = getRoles(roles);
        return new User(username,password,authorities);
    }

    private List<GrantedAuthority> getRoles(String roles) {
        String[] roles1 = roles.split("-");
        List<String> list = Arrays.asList(roles1);
        List<GrantedAuthority> listRoles = new ArrayList<GrantedAuthority>();
        for (String s : list) {
            listRoles.add(new SimpleGrantedAuthority(s));
        }
        return listRoles;
    }
}
